package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否完成登录
 */
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // Spring框架提供的路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取本次请求的URL
        String requestURI = request.getRequestURI();    // /backend/index.html

        log.info("拦截到请求URL：{}", requestURI);

        // 2.定义不需要拦截的URL地址数组
        String[] urls = new String[]{
                "/employee/login",  // 登录页面
                "/employee/logout", // 退出登录
                "/backend/**",      // 后台页面的页面的静态资源
                "/front/**",        // 移动端页面的静态资源
                "/common/**",       // 公共资源
                "/user/login",      // 用户登录
                "/user/sendMsg",// 发送登录验证码
        };

        // 3.判断本次请求URL是否需要拦截
        boolean check = check(urls, requestURI);

        // 4.如果check为true则不需要处理，直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        // 5-1.如果需要处理，则判断用户是否登录

        if (request.getSession().getAttribute("employee") != null) {
            // 能进入说明已经登录，直接放行
            log.info("用户已登录，id:{}",request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);


            filterChain.doFilter(request, response);
            return;
        }

// 5-2.判断移动端用户是否登录

        if (request.getSession().getAttribute("user") != null) {
        // 能进入说明已经登录，直接放行
        log.info("用户已登录，id:{}",request.getSession().getAttribute("user"));

        Long userId = (Long) request.getSession().getAttribute("user");
        BaseContext.setCurrentId(userId);


        filterChain.doFilter(request, response);
        return;
    }
        log.info("用户未登录");
    //6.未登录

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


}
    // 核查请求URL是否在放行URL数组中，检查本次请求是否需要放行
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        // 循环完了都匹配不上就返回false
        return false;
    }
}